package com.sky.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.UserThreadLocalUtil;
import com.sky.vo.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * PROJECT_NAME: sky-take-out
 * NAME: EmployeeServiceImpl
 * USER: SHINIAN
 * DATE: 2022/12/12
 * DESCRIPTION : B端-员工信息服务层接口实现类
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    //注入员工持久层实现类Bean(MyBatis生成的代理对象)
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录方法
     *
     * @param employeeLoginDTO 员工登录信息的DTO(用户名+密码)
     * @return 查询到的员工信息
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        //获取参数中的用户名与密码
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        //根据用户名查询数据库中的数据
        Employee employee = employeeMapper.selectEmployeeByUsername(username);
        //处理异常情况（用户名不存在）与（密码不对）
        if (employee == null) {
            //账号不存在则抛出对应异常交给全局异常处理器处理
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //处理异常情况（密码错误）
        if (!SecureUtil.md5(password).equals(employee.getPassword())) {
            //密码错误则抛出对应异常交给全局异常处理器处理
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //处理异常情况（用户状态为禁用）
        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定则抛出对应异常交给全局异常处理器处理
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //执行到此处说明以上判断均失败员工信息合法正确则返回实体对象
        return employee;
    }

    /**
     * 员工分页查询
     * @param dto
     * @return
     */
    @Override
    public Result getPage(EmployeePageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Employee> pageList = employeeMapper.getpage(dto);
        PageResult result = PageResult.builder().total(pageList.getTotal()).records(pageList.getResult()).build();
        return Result.success(result);
    }

    /**
     * 新增员工
     * @param dto
     */
    @Override
    public void insertEmployee(EmployeeDTO dto) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto, employee);
        employee.setStatus(StatusConstant.DISABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.insertEmplyee(employee);
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Employee selectEmployeeById(Long id) {
        return employeeMapper.selectEmployeeById(id);
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    @Override
    public void updateEmployee(Integer status,EmployeeDTO employeeDTO) {
        employeeMapper.updateEmployee(status,employeeDTO);
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //根据员工id查询员工信息
        Employee employee = employeeMapper.selectEmployeeById(UserThreadLocalUtil.getUser());
        String dbPassword = employee.getPassword();
        String oldPassword = passwordEditDTO.getOldPassword();
        if (!dbPassword.equals(SecureUtil.md5(oldPassword))){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (SecureUtil.md5(oldPassword).equals(dbPassword)){
            throw new PasswordErrorException("原始密码与新密码一致，请重新输入");
        }

        employee.setPassword(SecureUtil.md5(passwordEditDTO.getNewPassword()));
        employee.setId(UserThreadLocalUtil.getUser());
        employeeMapper.editPassword(employee);
    }
}
